/**
 * Created by ke.ouyang on 19/10/29
 * Email ke.ouyang@huilianyi.com
 */
import React from "react";
import { connect } from "react-redux";
import moment from "moment";
import { messages, deepCopy } from "share/common";
import "styles/enterprise-manage/person-manage/person-info-display/person-info-display.scss";
import PIDService from "containers/enterprise-manage/person-manage/person-info-display/person-info-display.service";
import { Button, Icon, message, Radio, Form, Row, Col, Checkbox, Spin, Popover, Tabs, Dropdown, Menu } from "antd";
import IPhoneX from "components/iphone-x";
import Condition from "components/condition";
//Img
import maleImg from "images/user-male.png";
import femaleImg from "images/user-female.png";
import unknowImg from "images/user-unknow.png";
import emailImg from "images/personal-setting/email.png";
import jobIdImg from "images/personal-setting/jobId.png";
import phoneImg from "images/personal-setting/phone.png";
import arrowImg from "images/personal-setting/arrow.png";
import EmployeeInfo from "containers/enterprise-manage/person-manage/person-info-display/employee-info";
import constants from "share/constants";
import baseService from "share/base.service";
import creditViewService from "../../../credit/credit-view/credit-view.service";
const FormItem = Form.Item;
const { If } = Condition;
const TabPane = Tabs.TabPane;
const operationTypeObj = {
  1001: messages("common-1.key359") /*加分*/,
  1002: messages("common-1.key360") /*减分*/,
  1003: messages("common-1.key361") /*升级*/,
  1004: messages("common-1.key362") /*降级*/,
};
class PersonInfoDisplay extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false, //保存按钮是否 loading
      basicOption: [
        // { label: messages("basic-5.key95") /*姓名*/, value: "fullName" },
        { label: messages("common.user.id") /*工号*/, value: "employeeID" },
        { label: messages("basic-5.key380") /*手机*/, value: "mobile" },
        { label: messages("basic-5.key162") /*邮箱*/, value: "email" },
        {
          label: messages("basic-5.key382") /*人员类型*/,
          value: "employeeType",
        },
        {
          label: messages("basic-5.key278") /*直属领导*/,
          value: "directManager",
        },
        { label: messages("basic-5.key283") /*性别*/, value: "gender" },
        // { label: messages("basic-5.key282") /*生日*/, value: "birthday" },
        { label: messages("basic-5.key281") /*入职时间*/, value: "entryDate" },
      ],
      jobInfoOption: [
        { label: messages("basic-5.key1") /*公司*/, value: "company" },
        {
          label: messages("common.department") /*部门*/,
          value: "department",
        },
        { label: messages("basic-5.key163") /*职位*/, value: "title" },
        { label: messages("basic-5.key279") /*职务*/, value: "duty" },
        { label: messages("basic-5.key280") /*级别*/, value: "rank" },
        { label: messages("basic-5.key412") /*主岗*/, value: "companyMainPosition" },
      ],
      previewClient: "pc",
      formSetting: {},
      userInfo: {},
      avatar: "",
      activeKey: "job",
      operationType: undefined,
      creditInfo: {},
      creditList: [],
      tableLoading: false,
    };
  }

  componentWillMount() {
    this.getFormSetting();
    this.getPersonDetail();
    this.getCreditInfo();
    this.getCreditList();
  }

  getFormSetting = () => {
    PIDService.getFormSetting()
      .then((res) => {
        this.setState({
          formSetting: res.data,
        });
      })
      .catch((err) => {});
  };

  getPersonDetail = () => {
    const { user } = this.props;
    PIDService.getPersonDetail(user.userOID) //获取用户信息
      .then((res) => {
        this.setState({
          userInfo: res.data,
          loading: false,
        });
      });
    if (user.avatar === null) {
      //设置预览头像
      if (user.gender === 0) {
        this.setState({
          avatar: maleImg,
        });
      } else if (user.gender === 1) {
        this.setState({
          avatar: femaleImg,
        });
      } else {
        this.setState({
          avatar: unknowImg,
        });
      }
    } else {
      this.setState({
        avatar: user.avatar,
      });
    }
  };

  //返回上一页
  handleCancel = () => {
    window.history.back();
  };
  handleSubmit = (e) => {
    this.setState({
      loading: true,
    });
    const { formSetting } = this.state;
    e.preventDefault();
    PIDService.updateFormSetting(formSetting)
      .then((res) => {
        this.getFormSetting();
        message.success(messages("basic-5.key463") /*保存成功*/);
        this.setState({
          loading: false,
        });
      })
      .catch((err) => {
        message.error(messages("common.save.filed") /*保存失败*/);
        this.setState({
          loading: false,
        });
      });
  };
  setPreviewClient = (e) => {
    this.setState({
      previewClient: e.target.value,
    });
  };

  changeFormSetting = (e, attr) => {
    let { formSetting, jobInfoOption } = this.state;
    let checked = e.target.checked;
    formSetting[attr] = checked;
    if (attr === "job") {
      jobInfoOption.forEach((item) => (formSetting[item.value] = checked));
      if (!checked) {
        this.setState({
          activeKey: "credit",
        });
      }
    } else if (attr === "credit") {
      if (!checked) {
        this.setState({
          activeKey: "job",
        });
      }
    } else {
      formSetting.job = jobInfoOption.some((item) => formSetting[item.value]);
    }
    this.setState({
      formSetting,
    });
  };
  //烦的来了…… 渲染 岗位信息
  renderPosition = () => {
    const { userInfo, formSetting } = this.state;
    const list = userInfo.companyWithUserJobsDTOList;
    return (
      list &&
      list.map((list) => {
        return (
          <div className="one-company">
            <If value={formSetting.company}>
              <div className="company-name-display">
                <span className="square" />
                <span className="name">{list && (list.companyName || "-")}</span>
              </div>
            </If>
            {list &&
              list.userJobsDTOList.map((item) => {
                return (
                  <If value={formSetting.title || formSetting.department || formSetting.duty || formSetting.rank}>
                    <div
                      className={
                        item.companyMainPosition && formSetting.companyMainPosition
                          ? "single-job-card-main"
                          : "single-job-card-other"
                      }
                    >
                      <If value={formSetting.title}>
                        <div className="job-title">{item.position}</div>
                      </If>
                      <div className={formSetting.title ? "job-detail" : "job-detail-on"}>
                        {this.renderDetail(item)}
                      </div>
                      <If value={item.companyMainPosition && formSetting.companyMainPosition}>
                        <span className="main-stamp">{messages("basic-5.key412") /*主岗*/}</span>
                      </If>
                    </div>
                  </If>
                );
              })}
          </div>
        );
      })
    );
  };
  renderDetail = (data) => {
    //渲染岗位详情字段
    const { formSetting } = this.state;
    const department = formSetting.department;
    const duty = formSetting.duty;
    const rank = formSetting.rank;
    const arr = [];
    if (department) {
      arr.push(data.departmentName || "-");
    }
    if (duty) {
      arr.push(data.duty || "-");
    }
    if (rank) {
      arr.push(data.rank || "-");
    }
    return arr.map((item) => item).join(" | ");
  };

  TabChange = (activeKey) => {
    this.setState({
      activeKey,
    });
  };

  getCreditInfo = () => {
    this.setState({ userLoading: true });
    creditViewService
      .getUserCreditInfo()
      .then((res) => {
        this.setState({ creditInfo: res.data, userLoading: false });
      })
      .catch((err) => {
        this.setState({ userLoading: false });
      });
  };

  renderCredit = () => {
    const { creditInfo, creditList, tableLoading, operationType } = this.state;
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        {[{ text: messages("common.all") /*全部*/, value: 0 }].concat(constants.creditRuleOperation).map((item) => (
          <Menu.Item key={item.value}>{item.text}</Menu.Item>
        ))}
      </Menu>
    );
    const result = (record) => {
      return (
        {
          1001: `${record.changeScore}`,
          1002: `-${record.changeScore}`,
          1003: `${record.changeRank}`,
        }[record.operationType] || `-${record.changeRank}`
      );
    };
    return (
      <div>
        <div className="credit-info-block">
          <span className="f-left">
            {messages("common-1.key368") /*信用等级*/}：{creditInfo.creditRank}
          </span>
          <span className="f-right">
            {messages("common-1.key367") /*信用分*/}：{creditInfo.score}
          </span>
        </div>
        <div className="clear" />
        <div className="credit-info-buttons">
          <Dropdown overlay={menu}>
            <Button className="credit-info-button">
              {operationTypeObj[operationType] || messages("common.all") /*全部*/}
              <span className="credit-info-icon" />
            </Button>
          </Dropdown>
        </div>
        <div className="credit-info-list">
          {tableLoading ? (
            <Spin spinning={tableLoading} />
          ) : (
            creditList.map((item) => {
              return (
                <div className={item.status === 1002 ? "credit-info-invalid" : "credit-info-valid"}>
                  <div>
                    <span className="f-left credit-info-comment text-ellipsis">{item.comment}</span>
                    <span
                      className={this.classNames({
                        "credit-info-plus": [1001, 1003].includes(item.operationType),
                        "credit-info-minus": ![1001, 1003].includes(item.operationType),
                        "f-right": true,
                      })}
                    >
                      {result(item)}
                    </span>
                  </div>
                  <div className="clear" />
                  <div>
                    <span className="f-left credit-info-date">
                      {item.lastModifiedDate ? new Date(item.lastModifiedDate).format("yyyy-MM-dd") : "-"}
                    </span>
                    {item.status === 1002 && (
                      <span className="f-left credit-info-abandon">{messages("finance-3.key9") /*作废*/}</span>
                    )}
                    <span className="f-right credit-info-date">
                      {operationTypeObj[item.operationType] || messages("common-1.key362") /*降级*/}
                    </span>
                  </div>
                </div>
              );
            })
          )}
        </div>
        <div className="clear" />
      </div>
    );
  };

  getCreditList = () => {
    const { operationType } = this.state;
    const { userOID } = this.props.user;
    let params = { userOID, page: 0, size: 10000 };
    if (operationType && operationType !== "0") {
      params.operationType = operationType;
    } else {
      delete params.operationType;
    }
    this.setState({ tableLoading: true });
    baseService
      .getHonestHistory(params)
      .then((res) => {
        this.setState({
          creditList: res.data,
          tableLoading: false,
        });
      })
      .catch((e) => {
        this.setState({ tableLoading: false });
        message.error(e.response.data.message);
      });
  };

  handleMenuClick = (item) => {
    this.setState({ operationType: item.key }, this.getCreditList);
  };

  render() {
    const { loading, basicOption, jobInfoOption, previewClient, userInfo, formSetting, avatar, activeKey } = this.state;
    const hasBasicInfo = formSetting.employeeID || formSetting.mobile || formSetting.email;
    const hasJobsInfo = formSetting.job;
    const hasOtherInfo =
      formSetting.employeeType || formSetting.directManager || formSetting.gender || formSetting.entryDate;
    const { user } = this.props;
    return (
      <div className="person-info-display-wrap">
        <Row>
          <Col span={8}>
            <div className="high-gap">
              <div className="preview-title inline-gap">{messages("common.baseInfo") /*基本信息*/}</div>
              {basicOption.map((item) => {
                return (
                  <Checkbox checked={formSetting[item.value]} onChange={(e) => this.changeFormSetting(e, item.value)}>
                    {item.label}
                  </Checkbox>
                );
              })}
            </div>
            <div className="high-gap">
              <div className="bottom-gap">
                <Checkbox checked={formSetting.job} onChange={(e) => this.changeFormSetting(e, "job")}>
                  <span className="preview-title">{messages("basic-5.key419") /*岗位信息*/}</span>
                </Checkbox>
              </div>
              {jobInfoOption.map((item) => {
                return (
                  <Checkbox checked={formSetting[item.value]} onChange={(e) => this.changeFormSetting(e, item.value)}>
                    {item.label}
                  </Checkbox>
                );
              })}
            </div>
            <div className="preview-title high-gap">
              <Checkbox checked={formSetting.credit} onChange={(e) => this.changeFormSetting(e, "credit")}>
                <span className="preview-title">{messages("basic-3.key61") /*信用*/}</span>
              </Checkbox>
            </div>
            <div>
              <Button type="primary" loading={loading} onClick={this.handleSubmit} htmlType="submit">
                {messages("common.save") /*保存*/}
              </Button>
              <Button onClick={this.handleCancel} style={{ marginLeft: 8 }}>
                {messages("common.back") /*返回*/}
              </Button>
            </div>
          </Col>
          <Col span={16}>
            <div className="style-preview-wrap">
              <div className="preview-title">{messages("basic-5.key918") /*样式预览*/}</div>
              <div className="inline-gap">
                <Radio.Group value={previewClient} onChange={this.setPreviewClient}>
                  <Radio.Button value="pc">{messages("basic-5.key919") /*WEB预览*/}</Radio.Button>
                  <Radio.Button value="app">{messages("basic-5.key920") /*APP预览*/}</Radio.Button>
                </Radio.Group>
              </div>
              {previewClient === "app" ? (
                <div className="phone-wrap">
                  <IPhoneX type="iPhoneX" title={messages("basic-5.key465") /*个人信息*/}>
                    <div className="card-background">
                      <div className="main-card">
                        <div className="avatar-card">
                          <div className="avatar">
                            <img className="avatar-img" src={avatar} alt="" />
                          </div>
                          <div className="edit-avatar">
                            <span className="edit">{messages("basic-5.key466") /*编辑头像*/}</span>
                            <img className="img" src={arrowImg} alt="" />
                          </div>
                        </div>
                        <div className={hasJobsInfo ? "main-info-card have-bottom-line" : "main-info-card"}>
                          <If value={formSetting.fullName}>
                            <div className="name">{userInfo.fullName || "-"}</div>
                          </If>
                          <div className={hasBasicInfo ? "detail-info margin-top12" : "detail-info"}>
                            {[
                              { key: "employeeID", src: jobIdImg },
                              { key: "mobile", src: phoneImg },
                              { key: "email", src: emailImg },
                            ].map((item) => {
                              return formSetting[item.key] ? (
                                <div>
                                  <img className="thumbnail-img" src={item.src} alt="" />
                                  {userInfo[item.key] || "-"}
                                </div>
                              ) : null;
                            })}
                          </div>
                          <div
                            className={`${hasJobsInfo ? "other-info padding-bottom" : "other-info"} ${
                              hasOtherInfo ? "margin-top12" : ""
                            }`}
                          >
                            {basicOption.map((item) => {
                              return ["employeeType", "directManager", "gender"].includes(item.value) &&
                                formSetting[item.value] ? (
                                <div>
                                  {item.label}：
                                  {item.value === "directManager" ? userInfo.directManagerName || "-" : "-"}
                                </div>
                              ) : formSetting.entryDate ? (
                                <div>
                                  {item.label}：{moment(userInfo.entryTime).format("YYYY/MM/DD")}
                                </div>
                              ) : null;
                            })}
                          </div>
                        </div>
                        <Tabs onChange={this.TabChange} activeKey={activeKey}>
                          {formSetting.job && <TabPane tab={messages("basic-5.key419") /*岗位信息*/} key={"job"} />}
                          {formSetting.credit && (
                            <TabPane tab={messages("basic-5.key927") /*信用明细*/} key={"credit"} />
                          )}
                        </Tabs>
                        {activeKey === "job" && formSetting.job && (
                          <div className="job-info-card">
                            <div className="job-info-title">{messages("basic-5.key419") /*岗位信息*/}</div>
                            {this.renderPosition()}
                          </div>
                        )}
                        {activeKey === "credit" && formSetting.credit && this.renderCredit()}
                      </div>
                    </div>
                  </IPhoneX>
                </div>
              ) : (
                <div className="employee-info-container">
                  <div className="employee-info-title">{messages("common-1.key570") /*员工信息*/}</div>
                  <EmployeeInfo
                    params={{ userOID: user.userOID }}
                    showCredit={formSetting.credit}
                    showJob={formSetting.job}
                    positionChangeDate={false}
                    basicInfoFields={basicOption.filter((item) => formSetting[item.value])}
                    positionInfoFields={jobInfoOption.filter((item) => formSetting[item.value])}
                  />
                </div>
              )}
            </div>
          </Col>
        </Row>
      </div>
    );
  }
}

PersonInfoDisplay.contextTypes = {
  router: React.PropTypes.object,
};

const wrappedPersonInfoDisplay = Form.create()(PersonInfoDisplay);

function mapStateToProps(state) {
  return {
    isOldCompany: state.login.isOldCompany,
    profile: state.login.profile,
    user: state.login.user,
    company: state.login.company,
    currentPageRoute: state.main.currentPageRoute,
    language: state.main.language,
  };
}

export default connect(mapStateToProps)(wrappedPersonInfoDisplay);
